package com.restaurant.web;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.multipart.MultipartFile;

import com.restaurant.domain.Foodtype;
import com.restaurant.domain.Menu;
import com.restaurant.domain.Menucategory;
import com.restaurant.proxies.MenuItemProxy;
import com.restaurant.service.FoodtypeService;
import com.restaurant.service.MenuService;
import com.restaurant.service.MenucategoryService;
import com.restaurant.validators.MenuItemFormDeleteValidator;
import com.restaurant.validators.MenuItemFormValidator;

@Component
@RequestMapping("/action/menuitem.do")
@SessionAttributes("menuItemProxy")
public class MenuItemFormController {

	private final String queryLoadAllMenu = "from Menu where isdeleted = false";
	private final String queryLoadAllMenucategory = "from Menucategory where isdeleted = false";
	private final String queryLoadAllFoodtype = "from Foodtype where isdeleted = false";
	
	@Autowired
	private MenuItemFormValidator menuItemFormValidator;
	
	@Autowired
	private MenuItemFormDeleteValidator menuItemFormDeleteValidator;
	
	@Autowired
	private MenuService objMenuService;
	
	@Autowired
	private MenucategoryService objMenucategoryService;
	
	@Autowired
	private FoodtypeService objFoodtypeService;
	
	@RequestMapping(method=RequestMethod.GET)
	public String menuItemGETRequest(ModelMap map){
		MenuItemProxy menuItemProxy = new MenuItemProxy();
		Menu menu = new Menu();
		ArrayList<Menu> listMenu = null;
		ArrayList<Menucategory> listMenucategories = null;
		ArrayList<Foodtype> listFoodtypes = null;
		try {
			listMenu = (ArrayList<Menu>) objMenuService.loadByHql(queryLoadAllMenu);
		} catch (Exception e) {
			listMenu = new ArrayList<Menu>();
		}
		
		try {
			listFoodtypes = (ArrayList<Foodtype>) objFoodtypeService.loadByHql(queryLoadAllFoodtype);
		} catch (Exception e) {
			listFoodtypes = new ArrayList<Foodtype>();
		}
		
		try {
			listMenucategories = (ArrayList<Menucategory>) objMenucategoryService.loadByHql(queryLoadAllMenucategory);
		} catch (Exception e) {
			listMenucategories = new ArrayList<Menucategory>();
		}
		
		menuItemProxy.setMenu(menu);
		menuItemProxy.setListMenucategories(listMenucategories);
		menuItemProxy.setListFoodtypes(listFoodtypes);
		menuItemProxy.setListMenu(listMenu);
		
		map.addAttribute("menuItemProxy", menuItemProxy);
		return "MenuItem";
	}
	
	@RequestMapping(method=RequestMethod.POST)
	public String menuItemPOSTRequest(ModelMap map, @ModelAttribute MenuItemProxy menuItemProxy, BindingResult result, HttpServletRequest request, HttpServletResponse response){
		
		String action = request.getParameter("action");
				
		if(action.compareTo("addnew")==0){
			menuItemFormValidator.validate(menuItemProxy, result);
			if(result.hasErrors())
				return "MenuItem";
			
			Menu menu = menuItemProxy.getMenu();
			menu.setIsdeleted(false);
			if(menuItemProxy.getFileData().getSize() > 0){
				String imagePath = UUID.randomUUID() + menuItemProxy.getFileData().getOriginalFilename().substring(menuItemProxy.getFileData().getOriginalFilename().lastIndexOf("."));
				uploadFile(menuItemProxy.getFileData(), request, imagePath);
				menu.setImagepath(imagePath);
			}
			
			if(menuItemProxy.getFileDataIcon().getSize() > 0){
				String imagePath = UUID.randomUUID() + menuItemProxy.getFileDataIcon().getOriginalFilename().substring(menuItemProxy.getFileDataIcon().getOriginalFilename().lastIndexOf("."));
				uploadFile(menuItemProxy.getFileDataIcon(), request, imagePath);
				menu.setIconpath(imagePath);
			}
						
			try {
				objMenuService.addOrModify(menu);
			} catch (Exception e) {
				return "redirect:menuitem.do";
			}
			
			menuItemProxy.setMenu(new Menu());
		}else if(action.compareTo("edit")==0){
			Menu menu = null;
			try {
				menu = objMenuService.loadByPrimaryKey(Long.parseLong(request.getParameter("id")));
				menuItemProxy.setMenu(menu);
			} catch (Exception e) {
				return "redirect:menuitem.do";
			} 
		}else if(action.compareTo("del")==0){
			Menu menu = null;
			try {
				menu = objMenuService.loadByPrimaryKey(Long.parseLong(request.getParameter("id")));
			}catch(Exception e){
				return "redirect:menuitem.do";
			}
			menuItemFormDeleteValidator.validate(menu, result);
			if(result.hasErrors()){
				try {
					menuItemProxy.setListMenu((ArrayList<Menu>)objMenuService.loadByHql(queryLoadAllMenu));
				} catch (Exception e) {
					return "redirect:menuitem.do";
				}
				map.addAttribute("menuItemProxy", menuItemProxy);		
				return "MenuItem";
			}
			
			menu.setIsdeleted(true);
			try {
				objMenuService.addOrModify(menu);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}// end delete
		
		try {
			menuItemProxy.setListMenu((ArrayList<Menu>)objMenuService.loadByHql(queryLoadAllMenu));
		} catch (Exception e) {
			return "redirect:menuitem.do";
		}
		map.addAttribute("menuItemProxy", menuItemProxy);		
		return "MenuItem";
	}
	
	private void uploadFile(MultipartFile file, HttpServletRequest request, String imagePath){
		try{
		String fileName = null;
        InputStream inputStream = null;
        OutputStream outputStream = null;
        if (file.getSize() > 0) {
                inputStream = file.getInputStream();
                if (file.getSize() > 10000) {
//                        System.out.println("File Size:::" + file.getSize());
//                        return "/uploadfile";
                }
                
                fileName = request.getServletContext().getInitParameter("imagePath") + imagePath;
                outputStream = new FileOutputStream(fileName);
                int readBytes = 0;
                byte[] buffer = new byte[10000];
                while ((readBytes = inputStream.read(buffer, 0, 10000)) != -1) {
                        outputStream.write(buffer, 0, readBytes);
                }
                outputStream.close();
                inputStream.close();
        }
		}catch(IOException ex){
			ex.printStackTrace();
		}

	}	
	
}
